package com.aote.rs;


import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.WebApplicationException;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

import com.af.expression.Delegate;
import com.af.expression.Program;
import com.af.expression.Token;
import com.browsesoft.EntityManager;
import com.browsesoft.resource.Resource;
import com.browsesoft.resource.ResourcePlugin;
import com.browsesoft.user.User;
import org.springframework.stereotype.Component;

@Path("search")
@Component
public class SearchService {
	static Logger log = Logger.getLogger(SearchService.class);

	@GET
	@Path("{source}/{userid}")
	// 用于旧的银光系统，获取资源内容
	public String search(@PathParam("source") String source, @PathParam("userid") String userid) {
		return innerSearch(source, userid);
	}
	@POST
	// source: {source: 资源查找表达式, userid: 登录用户id}
	public String search(String str) {
		log.debug(str);
		System.out.println("+++"+str);
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			JSONObject json = new JSONObject(str);
			// 取当前登录用户id
			String[] names = JSONObject.getNames(json);
			String source;
			String userid;
			if (names.length == 1) {
				JSONObject jo = json.getJSONObject("data");
				userid = jo.getString("userid");
				source = jo.getString("source");
			}else {
				userid = json.getString("userid");			
				// 取执行表达式
				source = json.getString("source");
			}
			return this.innerSearch(source, userid);
		} catch (Exception e) {
			throw new WebApplicationException(e, 500);
		}
	}

	// 把查询结果转换成JSON数组或者对象
	private Object toJSON(Object obj) {
		// 如果是迭代器，把迭代器里的对象转换成JSON数组
		if(obj instanceof Iterator) {
			Iterator it = (Iterator) obj;
			JSONArray array = new JSONArray();
			while (it.hasNext()) {
				Object o = it.next();
				if (o instanceof  Resource) {
					Resource res = (Resource)o;
					JSONObject json = ResourcePlugin.toJSON(res);
					array.put(json);
				}
			}
			return array;
		}

		// 如果List，把List里的转换成JSON数组
		if(obj instanceof List) {
			List it = (List) obj;
			JSONArray array = new JSONArray();
			for(Object o : it) {
				if (o instanceof  Resource) {
					Resource res = (Resource)o;
					JSONObject json = ResourcePlugin.toJSON(res);
					array.put(json);
				}
			}
			return array;
		}

		// 如果是JSONArray, 把里面的资源转换成JSON对象
		if (obj instanceof  JSONArray) {
			JSONArray result = new JSONArray();
			JSONArray array = (JSONArray)obj;
			for(Object o :  array) {
				if (o instanceof  Resource) {
					Resource res = (Resource)o;
					JSONObject json = ResourcePlugin.toJSON(res);
					result.put(json);
				} else if(o instanceof  JSONObject) {
					result.put(o);
				}
			}
			return result;
		}

		// 如果是资源，把资源转换成JSON对象
		if (obj instanceof  Resource) {
			Resource res = (Resource)obj;
			JSONObject json = ResourcePlugin.toJSON(res);
			return json;
		}

		// 其它情况，不做处理
		return obj;
	}

	// 根据资源查找表达式以及当前用户获取资源子树
	private String innerSearch(String source, String userid) {
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			// 放置当前登录用户
			Object resource = EntityManager.getInstance().getObject(userid);
			params.put("this", resource);
			// 设置根资源
			Resource root = EntityManager.getInstance().getRoot();
			params.put("root", root);
			// 设置资源处理工具
			ResourcePlugin tool = new ResourcePlugin();
			params.put("tool", tool);
			
			// 执行表达式
			Program prog = new Program(source);
			// 解析
			Delegate d = prog.parse();
			Object result = d.invoke(params);
			// 把结果转换成JSON形式
			result = this.toJSON(result);
			if (result == null) {
				return null;
			}
			return result.toString();
		} catch (Exception e) {
			throw new WebApplicationException(e, 500);
		}
	}
}
